package tk.djcrazy.instantmessage.serviceImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import tk.djcrazy.instantmessage.domain.UserEntity;
import tk.djcrazy.instantmessage.service.IUserAvatarService;
import tk.djcrazy.instantmessage.service.IUserService;

public class UserAvatarServiceImpl implements IUserAvatarService {

	@Resource
	private IUserService userService;
	

	@Override
	public String storeAvatar(File file, String fileName) throws IOException {
		Date currentTime = new Date();
		String storePath = file.getParentFile().getParentFile()
				.getAbsolutePath() + "/avatarfile/";
		File folder = new File(storePath);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fileEx = fileName.substring(fileName.lastIndexOf("."));
		String storePathName = formatter.format(currentTime) + fileEx;
		FileInputStream in = new FileInputStream(file);
		File stoFile = new File(storePath, storePathName);
		FileOutputStream out = new FileOutputStream(stoFile);
		transferStream(in, out);
		return storePathName;
	}

	@Override
	public void saveUserAvatar(int id, String filePath) {
		UserEntity entity = userService.findById(id);
		entity.setAvatarPath(filePath);
		userService.save(entity);
	}

	/**
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	private void transferStream(FileInputStream in, FileOutputStream out)
			throws IOException {
		byte[] buffer = new byte[2048];
		while (true) {
			int ins = in.read(buffer);
			if (ins != -1) {
				out.write(buffer, 0, ins);
			} else {
				in.close();
				out.flush();
				out.close();
				break;
			}
		}
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
